package com.edu.filter;

import com.edu.utils.IPUtil;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author ZCN
 * @version 1.0
 * @date 2021/11/19 16:53
 */
public class LoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req=(HttpServletRequest)request;
        //返回此请求的 URL 的一部分，从协议名称一直到 HTTP 请求的第一行中的查询字符串。
        String reqURI=req.getRequestURI();
        //如果是登录则不用判断
        if (reqURI.endsWith("login.jsp")
                || reqURI.endsWith("login") || reqURI.endsWith("session")) {
            System.out.println(IPUtil.getIPAddress(req)+"正在登录...");
            chain.doFilter(request, response);
            return;
        }
        if(reqURI.endsWith("/index") || reqURI.endsWith("/complexhots") || reqURI.endsWith("/foodcomplex")
        || reqURI.endsWith("/complexcookrecomment") || reqURI.endsWith(".css")||reqURI.endsWith(".js")||reqURI.endsWith(".jpg")
                ||reqURI.endsWith(".gif")||reqURI.endsWith(".png")){
            chain.doFilter(request, response);
            return;
        }
        if(reqURI.contains("/front/pay/")){
            chain.doFilter(request, response);
            return;
        }
        if (reqURI.endsWith("register")) {
            System.out.println(IPUtil.getIPAddress(req)+"正在注册...");
            chain.doFilter(request, response);
            return;
        }
        //通过session判断是否登录，没登陆就直接返回到登陆界面
        HttpSession session = req.getSession();
        if (null == session.getAttribute("username")) {
            System.out.println("未登录");
            ((HttpServletResponse) response).sendRedirect("/login.jsp");
            return;
        } else {
            chain.doFilter(request, response);
        }




    }

    @Override
    public void destroy() {

    }
}
